package cn.ibizlab.todo.api.config;

import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/inform/{loginname}")
public class WebSocketChatServer {
    /**
     * 全部在线会话，使用线程安全的map存储
     * 以用户登录名称为key
     */
    private static Map<String, Session> onlineSessions = new ConcurrentHashMap<>();

    /**
     * 连接打开
     * @param session
     * @param loginname
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("loginname")String loginname){
        onlineSessions.put(loginname, session);
    }

    /**
     * 发生错误时
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error){
        error.printStackTrace();
    }

    /**
     * 收到消息
     * @param session
     * @param jsonStr
     */
    @OnMessage
    public void onMessage(Session session, String jsonStr){
        if(!"ping".equals(jsonStr)){
            Message message = JSON.parseObject(jsonStr, Message.class);
            if(message.getToUser() != null && message.getMsg() != null){
                sendMessageToUserList(Message.jsonStr(message.getFromUser(), message.getToUser(), message.getMsg()));
            }
        }else{
            try {
                session.getBasicRemote().sendText("pong");
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭前触发
     * @param session   用户session
     * @param loginname  用户登录名称
     */
    @OnClose
    public void onClose(Session session, @PathParam("loginname") String loginname) {
        onlineSessions.remove(loginname);
    }

    /**
     * 向任务相关人发送消息
     * @param jsonStr 消息内容
     */
    public static void sendMessageToUserList(String jsonStr){
        Message message = JSON.parseObject(jsonStr, Message.class);
        List<String> users = Arrays.asList(message.getToUser().split(";"));
        for(String loginname: users){
            if(onlineSessions.containsKey(loginname)){
                sendMessage(onlineSessions.get(loginname), jsonStr);
            }
            //这里持久化数据
        }
    }

    /**
     * 向客户端send信息
     * @param session 用户session
     * @param msg   消息内容
     */
    public static void sendMessage(Session session, String msg){
        try {
            session.getBasicRemote().sendText(msg);
        }catch (IOException e){
            e.printStackTrace();
        }
    }


}
